package org.masterinftel.scrumpmt.activities;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;

import org.masterinftel.scrumpmt.Constants;
import org.masterinftel.scrumpmt.R;
import org.masterinftel.scrumpmt.ScrumApplication;
import org.masterinftel.scrumpmt.adapters.ProductsListAdapter;
import org.masterinftel.scrumpmt.json.model.ColaboradorJSON;
import org.masterinftel.scrumpmt.json.model.ListColabAll;
import org.masterinftel.scrumpmt.json.model.ProductResponse;
import org.masterinftel.scrumpmt.json.model.ProductoJSON;
import org.masterinftel.scrumpmt.protocol.Protocol;
import org.masterinftel.scrumpmt.util.UtilNetwork;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;

public class ProductsListActivity extends ListActivity {

	/** Called when the activity is first created. */

	private List<ProductoJSON> getProduct() {

		return application.getProductos();
	}

	private TextView lblMensaje;
	private ListView lstOpciones;
	private List<ProductoJSON> productsList;
	private ScrumApplication application;
	private ProgressDialog progressDialog;
	private ProductResponse respuesta;
	private Context ctx;
	private AdapterContextMenuInfo info;
	private int selectedContextMenu;
	private Dialog dialog;
	private long prodID;

	// Manejador asincrono de las peticiones de los productos
	private final Handler handler = new Handler() {
		@Override
		public void handleMessage(final Message msg) {
			progressDialog.dismiss();
			switch (msg.what) {
			case 0:
				application.setSprints(respuesta.lSprint);
				// No hay ningun sprint en el producto
				if (respuesta.lSprint.size() == 0) {
					startActivity(new Intent(ctx, NewSprintActivity.class));
				} else {
					startActivity(new Intent(ctx, SprintsListActivity.class));
				}
				break;
			case 1:
				// application.setSprints(respuesta.lSprint);
				Intent intent = new Intent(ctx, EditProductActivity.class);
				intent.putExtra("position", selectedContextMenu);
				startActivity(intent);
				break;
			case 2:
				startActivity(new Intent(ctx, NewProductActivity.class));
				break;
			case 3:
				Intent intentC = new Intent(ctx, ColabActivity.class);
				intentC.putExtra("position", prodID);
				startActivity(intentC);
				break;
			}
		}

	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.productslist);
		setTitle("ScrumPMT - Productos");
		// creamos variables utiles para la aplicacion
		ctx = this;
		application = (ScrumApplication) getApplication();

		ArrayAdapter<ProductoJSON> adapter = new ProductsListAdapter(this,
				getProduct());
		// ProductsListAdapter adapter = new ProductsListAdapter(this,
		// getProduct());
		this.productsList = getProduct();

		setListAdapter(adapter);
		lstOpciones = this.getListView();

		// As� se ponen los fondos en las listView
		lstOpciones.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.scrumpmtbackground));
		registerForContextMenu(lstOpciones);

	}

	@Override
	protected void onListItemClick(ListView l, View v, final int position,
			long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		String n = productsList.get(position).getNombre();
		Log.i(Constants.LOGTAG, n);
		progressDialog = ProgressDialog.show(ctx, "Conectando...",
				" Obteniendo listado Sprints", true, false);
		new Thread() {
			public void run() {

				// Versi�n con preferencias
				SharedPreferences prefs = PreferenceManager
						.getDefaultSharedPreferences(ctx);
				String URLFrontController = prefs.getString(
						Constants.KEY_URL_PREFERENCE, "");
				String urlRest = URLFrontController + ";jsessionid="
						+ application.getSessionID() + "?action="
						+ Protocol.L_PRODUCTOS + "&value="
						+ productsList.get(position).getId();

				JsonReader reader = UtilNetwork.getJSON(urlRest);
				respuesta = new Gson().fromJson(reader, ProductResponse.class);
				application.setProductoSeleccionado(productsList.get(position)
						.getId());
				handler.sendEmptyMessage(0);
			}
		}.start();

		Log.w(Constants.LOGTAG, "L_SPRINT: " + " - ID producto: "
				+ productsList.get(position).getId());

	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();

		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
		menu.setHeaderTitle(productsList.get(info.position).getNombre());
		inflater.inflate(R.menu.productcontextmenu, menu);

	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		info = (AdapterContextMenuInfo) item.getMenuInfo();
		switch (item.getItemId()) {
		case R.id.open_product:
			// Utiliza Constants.LOGTAG para los tags de los logs Emilio!!
			Log.i(Constants.LOGTAG, "Lista["
					+ productsList.get(info.position).getNombre()
					+ "]: open pulsada!");

			String n = productsList.get(info.position).getNombre();
			Log.i(Constants.LOGTAG, n);
			progressDialog = ProgressDialog.show(ctx, "Conectando...",
					" Obteniendo listado Sprints", true, false);
			new Thread() {
				public void run() {
					ScrumApplication app = (ScrumApplication) getApplication();

					// Versi�n con preferencias
					SharedPreferences prefs = PreferenceManager
							.getDefaultSharedPreferences(ctx);
					String URLFrontController = prefs.getString(
							Constants.KEY_URL_PREFERENCE, "");
					String urlRest = URLFrontController + ";jsessionid="
							+ app.getSessionID() + "?action="
							+ Protocol.L_PRODUCTOS + "&value="
							+ productsList.get(info.position).getId();

					JsonReader reader = UtilNetwork.getJSON(urlRest);
					respuesta = new Gson().fromJson(reader,
							ProductResponse.class);
					application.setProductoSeleccionado(productsList.get(
							info.position).getId());
					handler.sendEmptyMessage(0);
				}
			}.start();

			Log.w(Constants.LOGTAG, "L_SPRINT: " + " - ID producto: "
					+ productsList.get(info.position).getId());

			return true;
		case R.id.edit_product:

			Log.i(Constants.LOGTAG, "Lista["
					+ productsList.get(info.position).getNombre()
					+ "]: edit pulsada!");
			selectedContextMenu = info.position;
			progressDialog = ProgressDialog.show(ctx, "Conectando...",
					" Obteniendo listado colaboradores", true, false);
			new Thread() {
				public void run() {
					SharedPreferences prefs = PreferenceManager
							.getDefaultSharedPreferences(ctx);
					String URLFrontController = prefs.getString(
							Constants.KEY_URL_PREFERENCE, "");
					String urlRest = URLFrontController + ";jsessionid="
							+ application.getSessionID() + "?action="
							+ Protocol.L_COLAB_ALL;
					Log.i(Constants.LOGTAG, "Le envio al server: " + urlRest);
					JsonReader reader = UtilNetwork.getJSON(urlRest);
					ListColabAll listJSON = new Gson().fromJson(reader,
							ListColabAll.class);

					application.setColabAll(listJSON.getAllColab());
					for (ColaboradorJSON c : application.getColabAll())
						Log.i(Constants.LOGTAG,
								"Recibo del server el colaborador: "
										+ c.getNombre());
					handler.sendEmptyMessage(1);
				}
			}.start();

			return true;
		case R.id.see_product:
			Log.i(Constants.LOGTAG, "Lista["
					+ productsList.get(info.position).getNombre()
					+ "]: see pulsada!");

			dialog = new Dialog(ProductsListActivity.this);
			dialog.setContentView(R.layout.productdetails);
			dialog.setTitle(productsList.get(info.position).getNombre());
			dialog.setCancelable(true);
			// there are a lot of settings, for dialog, check them all out!

			// set up text
			TextView desDetails = (TextView) dialog
					.findViewById(R.id.DesProductDetails);
			desDetails.setText("Descripción: "
					+ productsList.get(info.position).getDes());
			TextView custDetails = (TextView) dialog
					.findViewById(R.id.CustomerProductDetails);
			custDetails.setText("Cliente: "
					+ productsList.get(info.position).getNomcli());
			DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
			String fini = format.format(productsList.get(info.position)
					.getFecini());
			String ffin = format.format(productsList.get(info.position)
					.getFecfin());
			TextView startDetails = (TextView) dialog
					.findViewById(R.id.StartProductDetails);
			startDetails.setText("Fecha inicio: " + fini);
			TextView endDetails = (TextView) dialog
					.findViewById(R.id.EndProductDetails);
			endDetails.setText("Fecha fin: " + ffin);
			TextView hoursDetails = (TextView) dialog
					.findViewById(R.id.HoursProductDetails);
			hoursDetails.setText("Horas jornada: "
					+ productsList.get(info.position).getHorasJornada());
			TextView masterDetails = (TextView) dialog
					.findViewById(R.id.ScrumMasterProductDetails);
			masterDetails.setText("Scrum master: "
					+ productsList.get(info.position).getNombreMaster());

			// set up button
			Button button = (Button) dialog
					.findViewById(R.id.BtExitProductDetails);
			button.setOnClickListener(mExitProductDetails);
			// now that the dialog is set up, it's time to show it
			dialog.show();

			return true;
		case R.id.cols_product:
			Log.i(Constants.LOGTAG, "Lista["
					+ productsList.get(info.position).getNombre()
					+ "]: colaboradores pulsada!");
			progressDialog = ProgressDialog.show(ctx, "Conectando...",
					" Obteniendo listado Colaboradores", true, false);
			new Thread() {
				public void run() {
					prodID = productsList.get(info.position).getId();
					SharedPreferences prefs = PreferenceManager
							.getDefaultSharedPreferences(ctx);
					String URLFrontController = prefs.getString(
							Constants.KEY_URL_PREFERENCE, "");
					String urlRest = URLFrontController + ";jsessionid="
							+ application.getSessionID() + "?action="
							+ Protocol.L_COLAB_ALL;

					JsonReader reader = UtilNetwork.getJSON(urlRest);
					ListColabAll listJSON = new Gson().fromJson(reader,
							ListColabAll.class);
					application.setColabAll(listJSON.getAllColab());

					urlRest = URLFrontController + ";jsessionid="
							+ application.getSessionID() + "?action="
							+ Protocol.L_COLAB_PROD + "&value=" + prodID;

					reader = UtilNetwork.getJSON(urlRest);
					ListColabAll listAllJSON = new Gson().fromJson(reader,
							ListColabAll.class);
					application.setColabProd(listAllJSON.getAllColab());

					handler.sendEmptyMessage(3);
				}
			}.start();
			return true;
		case R.id.del_product:
			prodID = productsList.get(info.position).getId();
			SharedPreferences prefs = PreferenceManager
					.getDefaultSharedPreferences(ctx);
			String URLFrontController = prefs.getString(
					Constants.KEY_URL_PREFERENCE, "");
			String urlRest = URLFrontController + ";jsessionid="
					+ application.getSessionID() + "?action="
					+ Protocol.REMOVE_PROD + "&value=" + prodID;

			UtilNetwork.getJSON(urlRest);
			Log.i(Constants.LOGTAG, "Lista["
					+ productsList.get(info.position).getNombre()
					+ "]: del pulsada!");
			// Elimino el producto de las variables globales
			productsList.remove(info.position);
			ArrayAdapter<ProductoJSON> adapter = new ProductsListAdapter(this,
					getProduct());
			setListAdapter(adapter);
			return true;
		default:
			return super.onContextItemSelected(item);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.productlistmenu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.newproductoption:
			progressDialog = ProgressDialog.show(ctx, "Conectando...",
					" Obteniendo listado colaboradores", true, false);
			new Thread() {
				public void run() {
					ScrumApplication id = (ScrumApplication) getApplication();
					SharedPreferences prefs = PreferenceManager
							.getDefaultSharedPreferences(ctx);
					String URLFrontController = prefs.getString(
							Constants.KEY_URL_PREFERENCE, "");
					String urlRest = URLFrontController + ";jsessionid="
							+ id.getSessionID() + "?action="
							+ Protocol.L_COLAB_ALL;
					Log.i(Constants.LOGTAG, "Le envio al server: " + urlRest);
					JsonReader reader = UtilNetwork.getJSON(urlRest);
					ListColabAll listJSON = new Gson().fromJson(reader,
							ListColabAll.class);

					application.setColabAll(listJSON.getAllColab());
					handler.sendEmptyMessage(2);
				}
			}.start();

			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}

	OnClickListener mExitProductDetails = new OnClickListener() {
		@Override
		public void onClick(View v) {
			dialog.dismiss();
		}

	};

}
